package com.klun.compute;

import java.util.Arrays;

/**
 * 二进制加法
 */
public class BinaryCountTest {

	public static void main(String[] args) {
		String strB = "1011101";
		String strA = "11011";
		String[] arrayA = strA.split("");
		String[] arrayB = strB.split("");
		
		plus(arrayA,arrayB);
		
	}
	public static void plus(String[] arrayA,String[] arrayB){

		// 使a的长度大于b的长度
		if(arrayA.length < arrayB.length){
			String[] tempArray = arrayA;
			arrayA = arrayB;
			arrayB = tempArray;
		}
		int temp = 0;//进位值，初始设置为0
		int maxLength = 0;//定义字符串长度最大的值
		int lengthA = arrayA.length-1;
		int lengthB = arrayB.length-1;
		// 此处A的长度大于B的长度
		maxLength = lengthA;
		for (int i = lengthB; i >= 0 ; i--) {
			String strB = arrayB[i];
			String strA = arrayA[maxLength];
			int intA = Integer.parseInt(strA);
			int intB = Integer.parseInt(strB);
			int res = intA + intB + temp;
			if(res == 0){
				temp = 0;
			}else if(res == 1){
				arrayA[maxLength] = "1";
				temp = 0;
			} else if(res == 2){
				arrayA[maxLength] = "0";
				temp = 1;
			}else if(res == 3){
				arrayA[maxLength] = "1";
				temp = 1;
			}
			maxLength--;
			
		}
		
		for (int i = maxLength; i >= 0; i++) {
			if(temp == 0){
				break;
			}
			String strA = arrayA[i];
			int intA = Integer.parseInt(strA);
			int res = intA + temp;
			if(res == 1){
				arrayA[maxLength] = "1";
				temp = 0;
			} else if(res == 2){
				arrayA[maxLength] = "0";
				temp = 1;
			}
			
		}
		
			
		System.out.println("相加结果"+Arrays.toString(arrayA));
		
	}

}
